package com.dsbj.mp.icardservice.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.dsbj.common.msg.ResponseMessage;
import com.dsbj.mp.icardservice.entity.*;
import com.dsbj.mp.icardservice.model.MpUser;
import com.dsbj.mp.icardservice.service.RecommendService;
import com.dsbj.mp.icardservice.utils.PropertyUtil;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Decoder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/recommend")
public class RecommendController extends BaseController {

	@Resource
	private RecommendService recommendService;


	/**
	 * 获取所有公司
	 * @param
	 * @return
	 * wcm
	 */
	@RequestMapping("/getAllCompany")
	public ResponseMessage getAllCompany() {
		return recommendService.getAllCompany();
	}

	@RequestMapping("/save")
    public ResponseMessage save(@RequestBody Map<String, Object> map){
		MpUser wxUser=(MpUser)request.getAttribute("wxUser");
		Recommend recommend = null;
		String str = JSON.toJSONString(map, SerializerFeature.WriteMapNullValue);
		recommend = JSON.parseObject(str, new TypeReference<Recommend>() {}, Feature.OrderedField);

		//存入图片路径(新的文件会覆盖旧的文件)
		String imagePath = PropertyUtil.getImageFileRoot() + "NJ" + recommend.getIdcardno() + ".jpg";
		if (saveBase64ToImageFile(recommend.getPhotoBase64(), imagePath)) {
			recommend.setPersonalTrajectoryUrl(PropertyUtil.getImageUrlRoot() + "NJ" + recommend.getIdcardno() + ".jpg");
		}
		String idcardno = recommend.getIdcardno();
		recommend.setIdcardno(idcardno.toUpperCase());
		recommend.setReferenceno(wxUser.getEmployeeNo());//内建人工号
		recommend.setReferencename(wxUser.getName());//内建人姓名
		recommend.setCreateUser(wxUser.getName());
		recommend.setStatus(1);
		recommendService.save(recommend);
		return ResponseMessage.ok();
	}

	//对字节数组字符串进行Base64解码并生成图片
	private boolean saveBase64ToImageFile(String imgStr, String imagePath) {
		if (imgStr == null) //图像数据为空
			return false;
		BASE64Decoder decoder = new BASE64Decoder();
		try {
			//Base64解码
			byte[] b = decoder.decodeBuffer(imgStr);
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {//调整异常数据
					b[i] += 256;
				}
			}
			//生成jpeg图片
			OutputStream out = new FileOutputStream(imagePath);
			out.write(b);
			out.flush();
			out.close();
			return true;
		} catch (Exception e) {
			logger.error("将base64格式的字符串编码,并存入对应的图片文件中，发生错误!" + e.toString());
			return false;
		}
	}
}
